﻿using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Practices.Unity;
using Hopscotch.Common.Logging;
using Hopscotch.Domain.Common.Enums;
using Hopscotch.Server.EnqSignalRHost.Hubs;
using Hopscotch.Domain.Enquiry;

namespace Hopscotch.Application.FakeServer
{
    class Program
    {
        static readonly ILogger logger = AppLogger.CreateLogger("FakeServer");

        static void Main(string[] args)
        {
            logger.Info("Starting Fake Server...");

            IUnityContainer container = new UnityContainer();
            UnityConfiguration.ConfigureContainer(container);

            if (Environment.UserInteractive)
            {
                StartInteractive(container);
            }
            else
            {
                //ServiceBase.Run(new WindowsService());
            }
        }

        private static void StartInteractive(IUnityContainer container)
        {
            using (var wcfServiceManager = new WcfServiceManager(container))
            using (var signalRStartup = new SignalRManager(container))
            {
                wcfServiceManager.Start();
                signalRStartup.Start();

                logger.Info("Fake Server Started.");

                RunLoop();
                wcfServiceManager.CloseAll(); //move to dispose...
            }
        }

        private static void RunLoop()
        {
            while (true)
            {
                Console.WriteLine("Server running...");
                Console.WriteLine("Press <q> to quit");
                ConsoleKeyInfo ki = Console.ReadKey(true);

                if (ki.Key == ConsoleKey.T)
                {
                    Test();
                }
                if (ki.Key == ConsoleKey.Q)
                {
                    break;
                }
            }
        }

        static int id = 2000;
        private static void Test()
        {
            var hc = GlobalHost.ConnectionManager.GetHubContext<TradeEnqHub>();

            var t = new TradeEnq { Id = id, InstrumentId = 1000, Qty = 1000, Price = 101, Activity = TradeActivity.Buy, Memo = "COD" };
            id++;
            hc.Clients.All.addTrade(t);
        }
    }
}
